/**
 * Description:
 * Class Name:BatchTest
 * Date:2022/4/10 18:40
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第13章_MySQL数据库和JDBC编程._13_7_事务处理._13_7_3_JDBC使用批量更新;

import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Properties;

public class BatchTest {
    private String driver;
    private String url;
    private String user;
    private String pwd;

    public void initParam(String paramFilePath) throws Exception{
        Properties props = new Properties();
        props.load(new FileReader(paramFilePath));
        driver = props.getProperty("driver");
        url = props.getProperty("url");
        user = props.getProperty("user");
        pwd = props.getProperty("pwd");
    }

    public void insertBatch(String[] sqls) throws Exception{
        try (
                Connection connection = DriverManager.getConnection(url, user, pwd);
                ){
            // 关闭自动提交——也就是开启事务
            connection.setAutoCommit(false);

            try (
                    Statement statement = connection.createStatement()
                    ){
                // 将要批量操作的SQL语句使用addBatch()方法加入到statement中
                for (var sql :
                        sqls) {
                    statement.addBatch(sql);
                }
                // 添加完后批量进行执行
                statement.executeLargeBatch();
            }
            connection.commit();    // 这里是提交事务了，注意是Connection对象负责
        }
    }

    public static void main(String[] args) throws Exception{
        var bt = new BatchTest();
        bt.initParam("Chapter_13_mysql.ini");
        Class.forName(bt.driver);

        String[] sqls = new String[]{
                "insert into student_table values(null, 'aaa', 1)",
                "insert into student_table values(null, 'bbb', 1)",
                "insert into student_table values(null, 'ccc', 1)",
        };
        bt.insertBatch(sqls);
    }
}
